package com.naicheng.ivote.views;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.naicheng.ivote.R;
import com.naicheng.ivote.adapter.PublishOptionsListAdapter;
import com.naicheng.ivote.adapter.PublishShortcutListAdapter;
import com.naicheng.ivote.adapter.TitleSelectAdapter;
import com.naicheng.ivote.constant.ConstantMine;
import com.naicheng.ivote.doman.BaseRequestBean;
import com.naicheng.ivote.doman.BaseResponseEntity;
import com.naicheng.ivote.doman.PublicOptionsBean;
import com.naicheng.ivote.doman.PublicShrotcutBean;
import com.naicheng.ivote.doman.RuleBean;
import com.naicheng.ivote.doman.TitleSelectlistBean;
import com.naicheng.ivote.engin.BaseActivity;
import com.naicheng.ivote.engin.MyRequestQueen;
import com.naicheng.ivote.parser.BaseParser;
import com.naicheng.ivote.uiself.DialogZhidaoleActivity;
import com.naicheng.ivote.uiself.PublishShortLinearForListView;
import com.naicheng.ivote.uiself.PublishoptionLinearForListView;
import com.naicheng.ivote.uiself.ToastUtils;
import com.naicheng.ivote.utils.AppManager;
import com.naicheng.ivote.utils.MyPreferences;
import com.naicheng.ivote.volley.Request;
import com.naicheng.ivote.volley.VolleyError;
import com.naicheng.ivote.volley.Response.ErrorListener;
import com.naicheng.ivote.volley.Response.Listener;
import com.naicheng.ivote.volley.toolbox.JsonObjectRequest;

public class PublishMainActivity extends BaseActivity implements Callback {

	PublishMainActivity CTPMA = PublishMainActivity.this;
	private MyPreferences preference;
	AppManager appManager = AppManager.getAppManager();
	private LayoutInflater inflater;
	private HashMap<String, String> map;

	private Handler handler;
	// PopupWindow对象
	private PopupWindow selectPopupWindow = null;
	// 自定义Adapter
	private TitleSelectAdapter titleAdapter = null;
	private ArrayList<TitleSelectlistBean> titleList;
	private TitleSelectlistBean titlebean;
	// 展示所有下拉选项的ListView
	private ListView listView = null;

	private LinearLayout publish_main_type_title_ll;
	private TextView publish_main_type_title1;
	private TextView publish_main_type_title2;
	private TextView publish_main_title_tvnum;
	private TextView publish_main_content_tvnum;
	private TextView publish_main_jifen2_tv;
	private EditText publish_main_title_et;
	private EditText publish_main_content_et;
	private EditText publish_main_jifen_et;
	private Button publish_main_send_but;
	private Button publish_main_add_but;
	

	private PublishoptionLinearForListView publish_main_option_list;
	private PublishShortLinearForListView publish_main_short_list;

	private PublishOptionsListAdapter optionsadapter;
	private PublishShortcutListAdapter shortcutadapter;
	
	private ArrayList<PublicOptionsBean> optionslist;
	private ArrayList<PublicShrotcutBean> shrotcutlist;
	private ArrayList<PublicShrotcutBean> shrotcutlisttemp;
	
	private RuleBean jifenBean;

	@Override
	protected void setConentView() {
		setContentView(R.layout.activity_publish_main);
	}

	@Override
	protected void init() {

		preference = MyPreferences.getPrefer(CTPMA, "myconfig");
		inflater = getLayoutInflater();
		handler=new Handler(CTPMA);
		shrotcutlist = new ArrayList<PublicShrotcutBean>();
		shrotcutlisttemp = new ArrayList<PublicShrotcutBean>();
		titlebean = new TitleSelectlistBean();
		titleList = new ArrayList<TitleSelectlistBean>();
		optionslist=new ArrayList<PublicOptionsBean>();
		jifenBean=new RuleBean();

		publish_main_type_title1 = (TextView) findViewById(R.id.publish_main_type_title1);
		publish_main_type_title2 = (TextView) findViewById(R.id.publish_main_type_title2);
		publish_main_title_tvnum = (TextView) findViewById(R.id.publish_main_title_tvnum);
		publish_main_content_tvnum = (TextView) findViewById(R.id.publish_main_content_tvnum);
		publish_main_jifen2_tv = (TextView) findViewById(R.id.publish_main_jifen2_tv);
		publish_main_title_et = (EditText) findViewById(R.id.publish_main_title_et);
		publish_main_content_et = (EditText) findViewById(R.id.publish_main_content_et);
		publish_main_jifen_et = (EditText) findViewById(R.id.publish_main_jifen_et);
		publish_main_send_but = (Button) findViewById(R.id.publish_main_send_but);
		publish_main_add_but = (Button) findViewById(R.id.publish_main_add_but);

		publish_main_type_title_ll = (LinearLayout) findViewById(R.id.publish_main_type_title_ll);

		publish_main_option_list = (PublishoptionLinearForListView) findViewById(R.id.publish_main_option_list);
		publish_main_short_list = (PublishShortLinearForListView) findViewById(R.id.publish_main_short_list);

		
		publish_main_title_tvnum.setText(35+"");
		publish_main_content_tvnum.setText(999+"");
		
//		PublicShrotcutBean bean = new PublicShrotcutBean();
//		shortcutadapter = new PublishShortcutListAdapter(this, list);
//		publish_main_short_list.setAdapter(shortcutadapter);

	}

	@Override
	protected void processLogic() {
		
		mytext(publish_main_title_et,publish_main_title_tvnum,35);
		mytext(publish_main_content_et,publish_main_content_tvnum,999);
		
		//设置选项
		PublicOptionsBean bean1=new PublicOptionsBean();
		bean1.setSequence("A");
		bean1.setText("");
		optionslist.add(bean1);
		PublicOptionsBean bean2=new PublicOptionsBean();
		bean2.setSequence("B");
		bean2.setText("");
		optionslist.add(bean2);
		optionsadapter=new PublishOptionsListAdapter(CTPMA, optionslist, handler);
		publish_main_option_list.setAdapter(optionsadapter);

		// 检查网络是否连接
		if (ConstantMine.isNetConn) {
			getNetDataHottypelist();
			getNetDataShortcutlist();
			getIntegral();
		} else {
			ToastUtils.getCenterDownToast(CTPMA, "未发现网络连接，请检查网络！");
		}
	}

	@Override
	protected void setOnClickListener() {
		publish_main_type_title1.setOnClickListener(CTPMA);
		publish_main_type_title2.setOnClickListener(CTPMA);
		publish_main_send_but.setOnClickListener(CTPMA);
		publish_main_add_but.setOnClickListener(CTPMA);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.publish_main_type_title1:

			if (null == titleList) {
				ToastUtils.getCenterDownToast(CTPMA, "暂无数据！");
			} else {
				System.out.println("getWidth:"
						+ publish_main_type_title_ll.getWidth());
				initPopuWindow(publish_main_type_title_ll.getWidth());
				popupWindwShowing(publish_main_type_title_ll);
			}

			break;
		case R.id.publish_main_type_title2:
			if (null == titleList) {
				ToastUtils.getCenterDownToast(CTPMA, "暂无数据！");
			} else {
				System.out.println("getWidth:"
						+ publish_main_type_title_ll.getWidth());
				initPopuWindow(publish_main_type_title_ll.getWidth());
				popupWindwShowing(publish_main_type_title_ll);
			}
			break;
		case R.id.publish_main_send_but:
			boolean textflag=true;
			int jifen=0;
			if("".equals(publish_main_jifen_et.getText().toString())){
				
			}else{
				jifen=Integer.parseInt(publish_main_jifen_et.getText().toString());
			}
			
			for (int i = 0; i < optionslist.size(); i++) {
				if(null==optionslist.get(i).getText()){
					textflag=false;
					return;
				}
			}
			if("".equals(publish_main_title_et.getText().toString())||"".equals(publish_main_content_et.getText().toString())){
				startActivity(new Intent(CTPMA,DialogZhidaoleActivity.class));
			}else if(!textflag){
				startActivity(new Intent(CTPMA,DialogZhidaoleActivity.class));
			}else if(jifen>jifenBean.getIntegral()){
				startActivity(new Intent(CTPMA,DialogZhidaoleActivity.class));
			}else{
				publish();
			}
			
			
			ToastUtils.getCenterDownToast(CTPMA, "题目发布成功！");
			break;
		case R.id.publish_main_add_but:
			if(optionslist.size()>=6){
				ToastUtils.getCenterDownToast(CTPMA, "最多6个选项");
			}else{
				switch (optionslist.size()) {
				case 1:
					PublicOptionsBean bean1=new PublicOptionsBean();
					bean1.setSequence("B");
					bean1.setText("");
					optionslist.add(bean1);
					break;
				case 2:
					PublicOptionsBean bean2=new PublicOptionsBean();
					bean2.setSequence("C");
					bean2.setText("");
					optionslist.add(bean2);
					break;
				case 3:
					PublicOptionsBean bean3=new PublicOptionsBean();
					bean3.setSequence("D");
					bean3.setText("");
					optionslist.add(bean3);
					break;
				case 4:
					PublicOptionsBean bean4=new PublicOptionsBean();
					bean4.setSequence("E");
					bean4.setText("");
					optionslist.add(bean4);
					break;
				case 5:
					PublicOptionsBean bean5=new PublicOptionsBean();
					bean5.setSequence("F");
					bean5.setText("");
					optionslist.add(bean5);
					break;
				}
				optionsadapter=new PublishOptionsListAdapter(CTPMA, optionslist, handler);
				publish_main_option_list.setAdapter(optionsadapter);
			}
			
			break;

		}

	}

	/**
	 * 发布题目
	 */
	public void publish(){
		
//		map=new HashMap<String, String>();
////		map.put("userid", "1");
//		map.put("userid", ConstantMine.userid);
//		map.put("long", 0+"");
//		map.put("lat", 0+"");
//		map.put("type", titlebean.getId()+"");
//		map.put("title", publish_main_title_et.getText().toString());
//		map.put("content", publish_main_content_et.getText().toString());
//		map.put("answernumber", 1+"");
//		map.put("optionnumber", optionslist.size()+"");
//		map.put("options", JSON.parseArray(optionslist.toString()).toJSONString());
//		map.put("integral", publish_main_jifen_et.getText().toString());
//		
//		super.getDataFromServer("createquestionnaire", map, new Listener<JSONObject>() {
//			@Override
//			public void onResponse(JSONObject response) {
//				BaseResponseEntity<String> mResponse = new BaseParser<String>().parserString(response);
//				if (mResponse != null && mResponse.getState()) {
//					ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
////					startActivity(new Intent(CTHMA,HotDetailMainActivity.class));
//				}else{
//					ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
//				}
//			}
//			
//		}, CTPMA);
		
		HashMap<String, Object> map1=new HashMap<String, Object>();
		map1.put("userid", "1");
//		map1.put("userid", ConstantMine.userid);
		map1.put("long", 0+"");
		map1.put("lat", 0+"");
		map1.put("type", titlebean.getId()+"");
		map1.put("title", publish_main_title_et.getText().toString());
		map1.put("content", publish_main_content_et.getText().toString());
		map1.put("answernumber", 1+"");
		map1.put("optionnumber", optionslist.size()+"");
//		map1.put("options", JSON.parseArray(optionslist.toString()).toJSONString());
		map1.put("options", optionslist);
		map1.put("integral", publish_main_jifen_et.getText().toString());
		
		ErrorListener errorListener = new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Toast.makeText(CTPMA, "网络不给力呀！请重试！", Toast.LENGTH_LONG).show();
			}
		};

		BaseRequestBean bean = new BaseRequestBean("createquestionnaire");
		
		map1.putAll(bean.toMap());
		JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, ConstantMine.url,
				new JSONObject(map1), new Listener<JSONObject>(){
					@Override
					public void onResponse(JSONObject response) {
						BaseResponseEntity<String> mResponse = new BaseParser<String>().parserString(response);
						if (mResponse != null && mResponse.getState()) {
							ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
//							startActivity(new Intent(CTHMA,HotDetailMainActivity.class));
						}else{
							ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
						}
						
					}
			
		}, errorListener);
		MyRequestQueen.getQueenInstance(CTPMA).addTask(jor);
		
	}
	
	/**
	 * 输入框控制方法
	 */
	public void mytext(final EditText editText,final TextView textView,final int maxnum){
		
		editText.addTextChangedListener(new TextWatcher() {
    		private CharSequence temp;  
            private int selectionStart ;  
            private int selectionEnd ; 
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				textView.setText((maxnum-temp.length())+"");
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;  
			}
			@Override
			public void afterTextChanged(Editable s) {
				selectionStart = editText.getSelectionStart();  
                selectionEnd = editText.getSelectionEnd();  
                if (temp.length() > maxnum) {  
                    s.delete(selectionStart-1, selectionEnd);  
                    int tempSelection = selectionStart;  
                    editText.setText(s);  
                    editText.setSelection(tempSelection);  
                }  
				
			}
		});
		
	}
	
	/**
	 * 获取热榜标题列表
	 */
	public void getNetDataHottypelist() {

		map = new HashMap<String, String>();
		super.getDataFromServer("type", map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<TitleSelectlistBean> mResponse = new BaseParser<TitleSelectlistBean>()
						.parserCollection(response, TitleSelectlistBean.class);
				if (mResponse != null && mResponse.getState()) {
					titleList = (ArrayList<TitleSelectlistBean>) mResponse
							.getData();
					System.out.println(titleList.size());
					publish_main_type_title1.setClickable(true);
					publish_main_type_title2.setClickable(true);
					for (int i = 0; i < titleList.size(); i++) {
						if (titleList.get(i).isDefault()) {
							publish_main_type_title1.setText(titleList.get(i)
									.getName());
						}
					}
				} else {
					ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
				}
			}

		}, CTPMA);

	}
	
	/**
	 * 获取快捷键列表
	 */
	public void getNetDataShortcutlist() {
		
		map = new HashMap<String, String>();
		super.getDataFromServer("shortcutkeys", map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<PublicShrotcutBean> mResponse = new BaseParser<PublicShrotcutBean>()
						.parserCollection(response, PublicShrotcutBean.class);
				if (mResponse != null && mResponse.getState()) {
					shrotcutlist = (ArrayList<PublicShrotcutBean>) mResponse.getData();
					System.out.println(shrotcutlist.size());
					if(null!=shrotcutlist){
						shortcutadapter = new PublishShortcutListAdapter(CTPMA, shrotcutlist,handler);
						publish_main_short_list.setAdapter(shortcutadapter);
						for (int i = 0; i < shrotcutlist.size(); i++) {
							shrotcutlisttemp.add(shrotcutlist.get(i));
						}
					}
					
				} else {
					ToastUtils.getCenterDownToast(CTPMA, mResponse.getMsg());
				}
			}
			
		}, CTPMA);
		
	}
	/**
	 * 获得积分信息
	 */
	private void getIntegral() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("userid", ConstantMine.userid);
		super.getDataFromServer("myintegral", map, new Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				System.out.println("response------>" + response.toString());
				BaseResponseEntity<RuleBean> mResponse = new BaseParser<RuleBean>()
						.parserDomain(response, RuleBean.class);
				if (mResponse != null && mResponse.getState()) {
					jifenBean = mResponse.getSingleDomain();
					publish_main_jifen2_tv.setText(jifenBean.getIntegral()+"分");
				}

			}
		}, this);
	}
	
	
	/**
	 * 初始化PopupWindow
	 */
	private void initPopuWindow(int mywidth) {
		// PopupWindow浮动下拉框布局
		View mywindow = CTPMA.getLayoutInflater().inflate(
				R.layout.activity_listselect_main, null);
		listView = (ListView) mywindow.findViewById(R.id.listselect_main_list);
		// 设置自定义Adapter
		titleAdapter = new TitleSelectAdapter(CTPMA, handler, titleList);
		listView.setAdapter(titleAdapter);
		selectPopupWindow = new PopupWindow(mywindow, mywidth,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT, true);
		selectPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		selectPopupWindow.setOutsideTouchable(true);
	}

	/**
	 * 显示PopupWindow窗口
	 * 
	 * @param popupwindow
	 */
	private void popupWindwShowing(View parent) {
		// 防止下拉框与文本框之间产生缝隙，影响界面美化
		selectPopupWindow.showAsDropDown(parent, 0, -3);
	}

	/**
	 * PopupWindow消失
	 */
	private void dismiss() {
		selectPopupWindow.dismiss();
	}

	@Override
	public boolean handleMessage(Message msg) {
		Bundle data = msg.getData();
		int id;
		switch (msg.what) {
		case 0:
			id = data.getInt("selIndex");
			publish_main_type_title1.setText(titleList.get(id).getName());
			titlebean = titleList.get(id);
			dismiss();
			break;
		
		case 1:
			//选项删除
			id = data.getInt("position");
			optionslist.remove(id);
			for (int i = 0; i < optionslist.size(); i++) {
				switch (i) {
				case 0:
					optionslist.get(i).setSequence("A");
					break;
				case 1:
					optionslist.get(i).setSequence("B");
					break;
				case 2:
					optionslist.get(i).setSequence("C");
					break;
				case 3:
					optionslist.get(i).setSequence("D");
					break;
				case 4:
					optionslist.get(i).setSequence("E");
					break;
				case 5:
					optionslist.get(i).setSequence("F");
					break;
				}
			}
			optionsadapter=new PublishOptionsListAdapter(CTPMA, optionslist, handler);
			publish_main_option_list.setAdapter(optionsadapter);
			System.out.println(id);
			break;
		case 2:
			//选项快捷键相应
			id = data.getInt("position");
			System.out.println(id);
			int num=shrotcutlist.get(id).getOptionnumber();
			System.out.println(shrotcutlist.get(id).getName()+shrotcutlist.get(id).getOptionnumber());
			if(0==num){
				ArrayList<PublicOptionsBean> optionslisttemp=new ArrayList<PublicOptionsBean>();
				for (int i = 0; i < 2; i++) {
					optionslisttemp.add(optionslist.get(i));
				}
				optionslist=optionslisttemp;
				optionsadapter=new PublishOptionsListAdapter(CTPMA, optionslist, handler);
				publish_main_option_list.setAdapter(optionsadapter);
			}else{
				optionslist=shrotcutlist.get(id).getOptions();
				if(null!=optionslist){
					optionsadapter=new PublishOptionsListAdapter(CTPMA, optionslist, handler);
					publish_main_option_list.setAdapter(optionsadapter);
				}
			}
			shrotcutlist=new ArrayList<PublicShrotcutBean>();
			for (int i = 0; i < shrotcutlisttemp.size(); i++) {
				shrotcutlist.add(shrotcutlisttemp.get(i));
			}
			shortcutadapter = new PublishShortcutListAdapter(CTPMA, shrotcutlist,handler);
			publish_main_short_list.setAdapter(shortcutadapter);
			break;
		
	
		}
		return false;
	}

}
